
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
        }
        #chat-container {
            width: 100%;
            max-width: 800px;
            margin: 0 auto;
        }
        #message-list {
            height: 300px;
            overflow-y: scroll;
            padding: 10px;
            border: 1px solid #ccc;
            margin-bottom: 10px;
        }
        #input-container {
            display: flex;
        }
        #input-container input {
            flex: 1;
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        #input-container button {
            margin-left: 10px;
            padding: 5px 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div id="chat-container">
        <div id="message-list"></div>
        <div id="input-container">
            <input type="text" id="message-input" placeholder="输入消息...">
            <button onclick="sendMessage()">发送</button>
        </div>
    </div>
    <script>
        async function send(message){
            // 发送到服务器保存
            try {
                const response = await fetch('http://10.200.32.26:5000/messages?message=' + encodeURIComponent(message), {
                    method: 'get' // 使用get方法发送消息
                });
                if (!response.ok) {
                    throw new Error('Failed to send message: ' + response.status);
                }
            } catch (error) {
                console.error('Error sending message:', error);
            }
        }

        function sendMessage() {
            const messageInput = document.getElementById('message-input');
            const messageList = document.getElementById('message-list');
            const message = messageInput.value;
            if (message) {
                send(message);
                const messageElement = document.createElement('div');
                messageElement.textContent = message;
                messageList.appendChild(messageElement);
                messageInput.value = ''; // 清空输入框
                messageList.scrollTop = messageList.scrollHeight; // 滚动到最底部显示最新消息
            } else {
                alert('请输入消息内容！'); // 提示用户输入消息内容，可根据需求自定义提示方式或样式
            }
        }

        // 从服务器加载历史消息并显示在聊天窗口
        async function loadMessages() {
            const messageList = document.getElementById('message-list');
            try {
                const response = await fetch('http://10.200.32.26:5000/messages', {
                    method: 'GET', // 使用GET方法获取历史消息
                });
                if (!response.ok) {
                    throw new Error('Failed to load messages: ' + response.status);
                }
                const messages = await response.json(); // 假设服务器返回JSON格式的历史消息数组
                messages.forEach(message => {
                    const messageElement = document.createElement('div');
                    messageElement.textContent = message;
                    messageList.appendChild(messageElement);
                });
                messageList.scrollTop = messageList.scrollHeight; // 滚动到最底部显示最新消息
            } catch (error) {
                console.error('Error loading messages:', error);
            }
        }

        // 在页面加载时加载消息
        loadMessages();
    </script>
<!-- Code injected by live-server -->
<script>
	// <![CDATA[  <-- For SVG support
	if ('WebSocket' in window) {
		(function () {
			function refreshCSS() {
				var sheets = [].slice.call(document.getElementsByTagName("link"));
				var head = document.getElementsByTagName("head")[0];
				for (var i = 0; i < sheets.length; ++i) {
					var elem = sheets[i];
					var parent = elem.parentElement || head;
					parent.removeChild(elem);
					var rel = elem.rel;
					if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") {
						var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, '');
						elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf());
					}
					parent.appendChild(elem);
				}
			}
			var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
			var address = protocol + window.location.host + window.location.pathname + '/ws';
			var socket = new WebSocket(address);
			socket.onmessage = function (msg) {
				if (msg.data == 'reload') window.location.reload();
				else if (msg.data == 'refreshcss') refreshCSS();
			};
			if (sessionStorage && !sessionStorage.getItem('IsThisFirstTime_Log_From_LiveServer')) {
				console.log('Live reload enabled.');
				sessionStorage.setItem('IsThisFirstTime_Log_From_LiveServer', true);
			}
		})();
	}
	else {
		console.error('Upgrade your browser. This Browser is NOT supported WebSocket for Live-Reloading.');
	}
	// ]]>
</script>
</body>
</html>